<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends BIT_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
	{
		parent::__construct();
		$this->header_views = array('admin/header');
		$this->footer_views = array('admin/footer');

		// Check if user is loggedin		
		$this->view_data['message'] = "";
	}
	
	private function isloggedin(){return (isset($this->session->userdata) && $this->session->userdata('loggedin')===TRUE);}

	public function index(){
		if(!$this->isloggedin())
		{
			$this->login();
		}
		else
		{
			$this->v('admin/home');	
		}
	}
	public function login(){

		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$form_rules = array(
			array(
				'field' => 'email',
				'label' => 'Epost',
				'rules' => 'trim|required|valid_email'
			),
			array(
				'field' => 'password',
				'label' => 'Lösenord',
				'rules' => 'trim|required|min_length[5]'
			)
		);
		$this->form_validation->set_message('valid_email','Epostadressen är inte giltig');
		$this->form_validation->set_message('required','Du måste fylla i fältet');
		$this->form_validation->set_message('min_length','Lösenordet är minst 5 tecken...');

		$this->form_validation->set_rules($form_rules);
		
		if($this->form_validation->run() == TRUE) {

			$email = $this->input->post('email');
			$password = md5($this->input->post('password'));
			$user = $this->db->get_where('accounts', array('email'=>$email,'password'=>$password))->result();
			
			if(count($user) > 0) {
				$this->session->set_userdata(array(
					'email'=>$user[0]->email,
					'userid'=>$user[0]->id,
					'loggedin'=>TRUE
					)
				);
				
				// Show startpage
				$this->v('admin/home');
			}
			else
			{
				// Handle post data upon login
				$this->view_data['message'] = "* Användarnamn eller lösenord är fel.";
				$this->v('admin/login');
			}
		}
		else{
			// Handle post data upon login
			$this->v('admin/login');
		}
	}

	public function logout(){
		$this->session->unset_userdata(array(
			'email'=>$user[0]->email,
			'userid'=>$user[0]->id,
			'loggedin'=>TRUE
			)
		);
		
		redirect('/');
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */